package org.esk.dablog.web.security;

import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.springframework.dao.DataAccessException;
import org.esk.dablog.service.UserManager;
import org.esk.dablog.model.Author;

/**
 * Acegi's UserDetails service implementation;
 * User: jc
 * Date: 01.12.2006
 * Time: 16:04:40
 * $Id:$
 */
public class BlogUserDetailsService implements UserDetailsService {
    private static final String ADMINISTRATOR_USER_NAME = "esk";

    private UserManager userManager;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        Author author = userManager.getAuthorByUsername(username);
        if (author == null) {
            throw new UsernameNotFoundException("User name " + username + " not found");
        }

        GrantedAuthority[] authorities;
        if (ADMINISTRATOR_USER_NAME.equals(author.getUsername())) {
            authorities = new GrantedAuthority[]{
                    new GrantedAuthorityImpl("ROLE_REGISTERED_USER"),
                    new GrantedAuthorityImpl("ROLE_SUPERVISOR")
            };
        } else {
            authorities = new GrantedAuthority[]{
                    new GrantedAuthorityImpl("ROLE_REGISTERED_USER")
            };

        }
        User u = new User(author.getUsername(), author.getPassword(), !author.isBlocked(), true, true, !author.isBlocked(),
                authorities);

        return u;
    }


    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }
}
